package com.lottery.service;

import com.alibaba.fastjson.JSON;
import com.lottery.constant.LotteryConstants;
import com.lottery.event.RetryEvent;
import com.lottery.model.AwardMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class RetryService {
    
    private static final String RETRY_COUNT_KEY = "retry:count:";
    private static final int MAX_RETRY_COUNT = 3;
    
    @Autowired
    private StringRedisTemplate redisTemplate;
    
    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;
    
    @EventListener
    public void handleRetryEvent(RetryEvent event) {
        String retryKey = RETRY_COUNT_KEY + event.getUserId() + ":" + event.getAwardId();
        
        try {
            // 获取重试次数
            String countStr = redisTemplate.opsForValue().get(retryKey);
            int count = countStr == null ? 0 : Integer.parseInt(countStr);
            
            if (count < MAX_RETRY_COUNT) {
                // 增加重试次数
                redisTemplate.opsForValue().set(retryKey, String.valueOf(count + 1), 24, TimeUnit.HOURS);
                
                // 延迟重试，每次重试时间翻倍
                Thread.sleep((long) Math.pow(2, count) * 1000);
                
                // 直接使用KafkaTemplate发送消息
                kafkaTemplate.send(LotteryConstants.TOPIC_AWARD, 
                    JSON.toJSONString(new AwardMessage(event.getUserId(), event.getAwardId())));
            } else {
                log.error("消息重试次数超过最大限制：userId={}, awardId={}", 
                    event.getUserId(), event.getAwardId());
            }
        } catch (Exception e) {
            log.error("重试消息处理失败: {}", event, e);
        }
    }
} 